package mq

import (
	"errors"
	"fmt"
	"github.com/nsqio/go-nsq"
	"time"
)

type NsqProducer struct {
	producer *nsq.Producer
}

func (p *NsqProducer) Publish(topic string, message string) (err error) {
	if message == "" {
		return errors.New("message is empty")
	}
	if err = p.producer.Publish(topic, []byte(message)); err != nil {
		fmt.Println(err)
		return err
	}
	return nil
}

// DeferredPublish 延迟消息
func (p *NsqProducer) DeferredPublish(topic string, delay time.Duration, message string) (err error) {
	if message == "" {
		return errors.New("message is empty")
	}
	if err = p.producer.DeferredPublish(topic, delay, []byte(message)); err != nil {
		fmt.Println(err)
		return err
	}
	return nil
}

func NewNsqProducer(addr string) (p *NsqProducer, err error) {
	var (
		config *nsq.Config
	)
	config = nsq.NewConfig()
	nsqP, err := nsq.NewProducer(addr, config)
	if err != nil {
		return nil, err
	}
	return &NsqProducer{
		producer: nsqP,
	}, nil
}
